package api

import (
	"context"
	"fmt"
	"os"
	"sync"

	"github.com/charmbracelet/huh"
	"github.com/charmbracelet/huh/spinner"
)

// var (
// TimeOut = 5 * time.Second
// )

func Chat() {
	var (
		wg      sync.WaitGroup
		input   string
		message string
	)

	for {
		form1 := inputBox(&input)
		addPwd(&input)
		addTree(&input)
		if err := form1.Run(); err == huh.ErrUserAborted {
			message = ""
			return
		}

		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
		action := func() {
			message = aiCmd(input, &wg)
			cancel()
		}
		go action()
		wg.Wait()
		spinner.New().Context(ctx).Run()

		form2 := chatTextBox(&message)

		if err := form2.Run(); err == nil {
			if err := runCommand(message); err != nil {
				fmt.Printf("Command execution error: %v\n", err)
			}
			return
		}
	}
}

func Normal(input string) {
	var (
		wg      sync.WaitGroup
		message string
	)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	action := func() {
		addPwd(&input)
		addTree(&input)
		message = aiCmd(input, &wg)
		cancel()
	}
	go action()
	wg.Wait()
	spinner.New().Context(ctx).Run()

	if err := runCommand(message); err != nil {
		fmt.Printf("Command execution error: %v\n", err)
	}
}

func Upload(input string) {
	var (
		wg      sync.WaitGroup
		cmdRes  []string
		message string
	)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	action := func() {
		addTree(&input)
		n, list := aiChoose(input, &wg)
		for i := 0; i < n; i++ {
			filePath, err := runCommandWithValue(list[i])
			if err != nil {
				cancel()
				fmt.Println("输入的文件名错误，请重新输入")
				os.Exit(0)
			}
			cmdRes = append(cmdRes, filePath)
		}
		addPwd(&input)
		addTree(&input)
		message = aiUpload(input, cmdRes, &wg)
		cancel()
	}
	go action()
	wg.Wait()
	spinner.New().Context(ctx).Run()

	form := chatTextBox(&message)
	if err := form.Run(); err == nil {
		if err := runCommand(message); err != nil {
			fmt.Printf("Command execution error: %v\n", err)
		}
	} else if err == huh.ErrUserAborted {
	} else {
		fmt.Printf("Command execution error: %v\n", err)
	}
}
